﻿using Newtonsoft.Json;
using OF.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace CGT.OP.Common
{
    /// <summary>
    /// 微信模板消息帮助类
    /// </summary>
    public class WxHelper
    {
        private string appid {
            get {
                return SiteUtility.GetAppSettings("WxAppID");
            }
        }
        private string secret
        {
            get
            {
                return SiteUtility.GetAppSettings("WxAppSecret");
            }
        }

    /// <summary>
    /// 
    /// </summary>
    public class AccessToken
        {
            public string access_token { get; set; }
            public int expires_in { get; set; }
            public DateTime CreateDate { get; set; }


        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        public string GetMenu()
        {
            string postUrl = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", GetAccessToken());
            var res = GetDataByPost(postUrl);
            return res;
        }

        /// <summary>
        /// 创建菜单
        /// </summary>
        /// <returns></returns>
        public string CreateMenu(string postData)
        {
            string postUrl = string.Format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}", GetAccessToken());
            var res = GetDataByPost(postUrl, postData);
            return res;
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="templateId"></param>
        /// <param name="toUser"></param>
        /// <param name="data"></param>
        /// <param name="linkUrl"></param>
        public void SendTemplete(string templateId, string toUser, object data, string linkUrl)
        {
            var token = GetAccessToken();
            var postUrl = string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}",
                token);
            //注：url和miniprogram都是非必填字段，若都不传则模板无跳转；若都传，会优先跳转至小程序。开发者可根据实际需要选择其中一种跳转方式即可。当用户的微信客户端版本不支持跳小程序时，将会跳转至url。
            var msgData = new
            {
                template_id = templateId,
                touser = toUser,
                data = data,
                url = linkUrl,//跳转到URL
                topcolor = "#FF0000", //已被腾讯禁用
                //miniprogram=new {//跳转到小程序
                //    //所需跳转到的小程序appid（该小程序appid必须与发模板消息的公众号是绑定关联关系）
                //    appid = "wxd9658c4601a224e7",
                //    pagepath = "pages/index/index"
                //},          


            };
            var j = JsonConvert.SerializeObject(msgData);
            //    Log4netLog.Debug("发送模板消息内容" + j);
            var res = GetDataByPost(postUrl, j);

            // Log4netLog.Debug("发送模板消息反回内容:" + res);
        }


        private string GetAccessToken()
        {
            var token = new AccessToken();
            var accessToken = CacheUtility.GetCache("accessToken", new string[] { });
            if (accessToken == null)
            {
                //获取TOKEN
                token = GetToken();
                CacheUtility.AddCache(token, "accessToken", new string[] { }, 100);

            }
            else
            {
                token = accessToken as AccessToken;
                //判断时间
                if (DateTime.Now > token.CreateDate.AddSeconds(token.expires_in))
                {
                    //获取TOKEN
                    token = GetToken();
                    CacheUtility.AddCache(token, "accessToken", new string[] { }, 100);
                }
            }


            var t = CacheUtility.GetCache("accessToken", new string[] { }) as AccessToken;
            return t.access_token;
        }

        private AccessToken GetToken()
        {
            string apiurl =
                $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
            string res = GetDataByPost(apiurl);
            var v = JsonConvert.DeserializeObject<AccessToken>(res);
            v.CreateDate = DateTime.Now;
            return v;
        }

        private string GetDataByPost(string url, string postData = "")
        {
            string result = "";
            byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(postData);
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = url;
                request.Accept = "*/*";
                request.Timeout = 30 * 1000;
                request.UserAgent =
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.Method = "POST";
                request.ContentLength = byteData.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(byteData, 0, byteData.Length);
                stream.Flush();
                stream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream backStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(backStream, Encoding.GetEncoding("UTF-8"));
                result = sr.ReadToEnd();
                sr.Close();
                backStream.Close();
                response.Close();
                request.Abort();
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
    }
}